import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_ncsjqz_getx/model/group_details_entity.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/commom/address_book/address_list_logic.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/commom/address_book/address_list_view.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/rong_base_logic.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/util/rong_widget.dart';
import 'package:flutter_ncsjqz_getx/util/get_user_util.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';
/// <summary>
/// author：zwb
/// dateTime： 2022/1/15 12:05
/// filePath： lib/page/rong_im/group/group_code_page.dart
/// desc: 群二维码
/// <summary>
///
class GroupCodePage extends StatefulWidget {
  final GroupDetailsData? groupDetailsData;

  const GroupCodePage({Key? key, this.groupDetailsData}) : super(key: key);

  @override
  _GroupCodePageState createState() => _GroupCodePageState();
}

class _GroupCodePageState extends State<GroupCodePage> {
  String codeStr = '';
  GlobalKey globalKey = GlobalKey();
  RongBaseLogic rongBaseLogic = Get.put(RongBaseLogic());
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Map map=Map();
    map['id']=widget.groupDetailsData!.groupId;//群聊id或者单聊
    map['type']=3;//群聊类型或者单聊
    map['name']=widget.groupDetailsData!.groupName;//群聊名称
    map['invitation_ryUserId']=getUserUtil().ryUserId;//邀请人融云id
    map['invitation_userId']=getUserUtil().userId;//邀请人
    map['invitation_nikeName']=getUserUtil().nikeName;//邀请人
    codeStr =json.encode(map);
    setState(() { });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey.shade100,
      appBar: RongWidget.appBarWidget(title: "群聊二维码名片"),
      body: Container(
        child:  Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            RepaintBoundary(
              key: globalKey,
              child: Container(
                width: Get.width,
                color: Colors.white,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      width: Get.width,
                      child: Row(
                        children: [
                          rongGroupPic(),
                          RongWidget.text("${widget.groupDetailsData!.groupName}"),
                        ],
                      ),
                    ),
                    Container(
                      width:Get.width / 1.8,
                      height:Get.width / 1.8,
                      margin: EdgeInsets.symmetric(vertical: 30),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(color: Colors.grey.shade200)
                      ),
                      child: Stack(
                        children: [
                          QrImage(
                            data: "$codeStr",
                            version: QrVersions.auto,
                            size: Get.width / 1.8,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(
              height: 20,
            ),
            Row(
              children: [
                Expanded(
                  child: OutlineButton(
                    shape: StadiumBorder(),
                    borderSide: BorderSide(color: Colors.green,),
                    child: RongWidget.text("保存图片",color: Colors.green),
                    onPressed: ()  async{
                      saveImg();
                    },
                  ),
                ),
                SizedBox(
                  width: 20,
                ),
                Expanded(child: RongWidget.gradientButton("发送给好友",circular: 40,onTap: () {
                  Get.to(()=>AddressListPage(type: 1,))!.then((value) async{
                    print(value);
                    if(value!=null){
                      sendImgMsg(value);
                    }
                  });
                }),),
              ],
            ),
          ],
        ),
        width: Get.width,
        padding: EdgeInsets.all(15),
      ),
    );
  }
  /// 群聊头像
  rongGroupPic() {
    // 成员数
    int picMax = widget.groupDetailsData!.users!.length;
    double height = 0.0;
    if(picMax >= 3){
      height = 50 / 3;
    }
    if(picMax == 2 || picMax == 3 || picMax == 4){
      height = 50 / 2;
    }
    if(picMax == 1){
      height = 50;
    }
    return Container(
      width: 67,
      height: 67,
      margin: EdgeInsets.symmetric(horizontal: 15,vertical: 15),
      padding: EdgeInsets.all(5),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey.shade200)
      ),
      child: Wrap(
        alignment: picMax == 3 ? WrapAlignment.center : WrapAlignment.start,
        runAlignment: picMax == 2 || picMax == 6 || picMax == 3 ? WrapAlignment.center : WrapAlignment.start,
        runSpacing: 5,
        spacing: 5,
        children: List.generate(picMax, (id){
          return RongWidget.imgNet('${widget.groupDetailsData!.users![id].picUrl ?? ""}',width: height ,height: height ,borderRadius: BorderRadius.circular(2));
        }),
      ),
    );
  }

  /// 保存图片
  Future<String> saveImg() async{
    String path = "";
    //检查是否有存储权限
    if (!await Permission.storage.request().isGranted){
      toast("没有存储权限，二维码保存失败");
    }else{
      //截图
      RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
      ui.Image image = await boundary.toImage();
      ByteData? byteData = await (image.toByteData(format: ui.ImageByteFormat.png));
      // 保存
      if (byteData != null) {
        final result = await ImageGallerySaver.saveImage(byteData.buffer.asUint8List(), );
        print(File(result["filePath"]));
        if(result["isSuccess"]){
          path = result["filePath"];
          toast("保存成功");
        }else{
          toast("保存失败");
        }
      }
    }
    return path;
  }

  saveImg1()async{
    //
    String path = "";
    //检查是否有存储权限
    if (!await Permission.storage.request().isGranted){
      toast("没有存储权限，二维码保存失败");
    }else{
      //截图
      RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
      ui.Image image = await boundary.toImage();
      ByteData? byteData = await (image.toByteData(format: ui.ImageByteFormat.png));
      // 保存
      if (byteData != null) {
        // final result = await ImageGallerySaver.saveImage(byteData.buffer.asUint8List(), );
        Directory? appDocDir = await getTemporaryDirectory();
        String appDocPath = appDocDir.path;
        print(appDocPath);
        File file = File(appDocPath+'/save_code.png');
        file.createSync(recursive: true);
        file.writeAsBytesSync(byteData.buffer.asUint8List());
        // final result  = await ImagesPicker.saveImageToAlbum(file, albumName: "${file.path}");
        path = file.path;
      }
    }
    return path;
  }
  /// 发送图片消息
  sendImgMsg(value) async{
    String path = await saveImg1();
    if(path == "") return;
    List<ContactInfo?> friendList = value;
    int count=0;
    for(int i=0;i<friendList.length;i++){
      ImageMessage imgMsg = ImageMessage.obtain(path);
      imgMsg.destructDuration = 0;
      Message? message = await  RongIMClient.sendMessage(3, friendList[i]!.ryUserId, imgMsg);
      RongIMClient.onMessageSend=(int? messageId, int? status, int? code){
        if(status == RCSentStatus.Failed){//消息发送失败
          toast("发送给${friendList[i]!.name}失败，请自行保存图片至本地");
        }else if(status==RCSentStatus.Sent){
          count++;
        }
        if(count==friendList.length){
          toast("群二维码发送成功");
          Get.back();
        }
      };
    }
  }
}
